package com.cn.qgx428.lazydiary.prump

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Vibrator
import android.support.v4.app.NotificationCompat
import android.text.TextUtils
import com.cn.qgx428.lazydiary.APP
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.extension.getCurrenTimePrecise
import java.util.*

/**
 * Created by qinguanxiong on 2018/4/8.
 */
abstract class BaseClock: IClockAlarm {

    var mAlarmTime: String = ""
    lateinit var mContext: Context

    // 竞争出来的对象
    var mObject: Any?

    constructor(){
        mContext = APP.getAppContext()
        mObject = compete()
        if (mObject != null)
            mAlarmTime = getAlarmTime()
    }


    //让同类自己先竞争提醒时间
    abstract fun compete():Any?

    //提醒时间到
    override fun isAlarm(): Boolean {
        return isAlarmTime()
    }

    /**
     * 自我检查，如果mObject为null说明此clcok不留着，返回null
     */
    public fun getRealClock(): BaseClock?{
        if (mObject == null){
            return null
        }
        return this
    }

    public fun isAlarmTime(): Boolean{
        val currentTime = Calendar.getInstance().getCurrenTimePrecise()
        if (TextUtils.isEmpty(mAlarmTime)){
            return false
        }
        if (currentTime.compareTo(mAlarmTime) == 1 ){
            return true
        } else {
            return false
        }

        return  false
    }

    /**
     * 发送通知
     */
    protected fun sendNotification(targetIntent: PendingIntent, nId: Int ,title: String, msg:String, smallIcon: Int = R.mipmap.ic_launcher){
        val builder = NotificationCompat.Builder(mContext)
        builder.setSmallIcon(smallIcon)
                .setContentTitle(title)
                .setContentText(msg)
                .setContentIntent(targetIntent)
        val manager: NotificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(nId, builder.build())
    }

    /**
     * 震动
     */
    public fun vibricate(mills: Long){
        val vib = mContext.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
        vib.vibrate(mills)
    }

}